<template>
  <div class="chat-container">
    <!-- 侧边栏 -->
    <div class="chat-sidebar" :class="{ 'is-open': isSidebarOpen }">
      <!-- 侧边栏顶部：用户信息和搜索框 -->
      <div class="sidebar-header">
        <div class="current-user-info">
          <div class="user-avatar">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="user-name">{{ currentUser?.nickname || currentUser?.username }}</div>
          <div class="user-actions">
            <el-button
              type="text"
              @click="goToSettings"
              style="font-size: 18px; color: var(--icon-color); margin-right: 10px;"
            >
              <el-icon><Setting /></el-icon>
            </el-button>
            <el-button
              type="text"
              @click="handleLogout"
              style="color: #f56c6c; font-size: 18px;"
            >
              <el-icon><SwitchButton /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索联系人..."
            prefix-icon="Search"
            clearable
          />
        </div>
      </div>

      <!-- 最近聊天列表 (或者用户列表) -->
      <div class="user-list">
        <div
          v-for="user in users"
          :key="user.id"
          class="user-item"
          :class="{ active: currentChatUser?.id === user.id }"
          @click="selectUser(user)"
        >
          <div class="user-avatar">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="user-item-content">
            <div class="user-item-header">
              <div class="user-name">{{ user.nickname || user.username }}</div>
              <div class="message-time">{{ user.lastMessage?.createdAt ? formatTime(user.lastMessage.createdAt) : '' }}</div>
            </div>
            <div class="user-item-footer">
              <div class="user-status">
                <span class="status-dot" :class="user.onlineStatus === 'ONLINE' ? 'online' : 'offline'"></span>
                {{ user.onlineStatus === 'ONLINE' ? '在线' : '离线' }}
              </div>
              <el-badge :value="user.unreadCount" :hidden="!user.unreadCount" class="item"></el-badge>
            </div>
            <div class="last-message">
              {{ user.lastMessage?.content || '暂无消息' }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main" @click="closeSidebarOnMobile">
      <!-- 聊天头部 -->
      <div class="chat-header" v-if="currentChatUser">
        <div class="chat-header-left">
          <el-button
            v-if="isMobile"
            type="text"
            @click.stop="toggleSidebar"
            style="margin-right: 10px; font-size: 20px; color: var(--icon-color);"
          >
            <el-icon><Fold /></el-icon>
          </el-button>
          <div class="user-avatar">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div>
            <div class="chat-header-name">{{ currentChatUser.nickname || currentChatUser.username }}</div>
            <div class="chat-header-status">
              <span class="status-dot" :class="currentChatUser.onlineStatus === 'ONLINE' ? 'online' : 'offline'"></span>
              {{ currentChatUser.onlineStatus === 'ONLINE' ? '在线' : '离线' }}
            </div>
          </div>
        </div>
        <div class="chat-header-right">
          <el-button type="text" style="color: var(--icon-color);"><el-icon><Search /></el-icon></el-button>
          <el-button type="text" style="color: var(--icon-color);"><el-icon><Phone /></el-icon></el-button>
          <el-button type="text" style="color: var(--icon-color);"><el-icon><VideoCamera /></el-icon></el-button>
          <el-button type="text" style="color: var(--icon-color);"><el-icon><MoreFilled /></el-icon></el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="chat-messages" ref="messagesRef">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message-item"
          :class="{ own: message.sender.id === currentUser?.id, 'is-recalled': message.isRecalled }"
        >
          <template v-if="!message.isRecalled">
            <div class="message-avatar">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="message-bubble-wrapper">
              <div class="message-content">
                <!-- 文本消息 -->
                <div v-if="message.messageType === 'TEXT'">
                  {{ message.content }}
                </div>

                <!-- 文件消息 -->
                <div v-else-if="message.messageType === 'FILE'" class="file-item">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <div class="file-info">
                    <div class="file-name">{{ message.fileName }}</div>
                    <div class="file-size">{{ formatFileSize(message.fileSize) }}</div>
                  </div>
                  <el-button
                    type="primary"
                    size="small"
                    @click="downloadFile(message.fileUrl, message.fileName)"
                  >
                    下载
                  </el-button>
                </div>
              </div>

              <div class="message-time">
                {{ formatTime(message.createdAt) }}
                <span
                  v-if="message.sender.id === currentUser?.id && !message.isRecalled && canRecall(message.createdAt)"
                  class="recall-button"
                  @click="recallMessage(message.id)"
                >
                  撤回
                </span>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="message-recall-container">
              <div class="message-recall">
                {{ message.content }}
              </div>
              <div class="message-time">
                {{ formatTime(message.createdAt) }}
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input" v-if="currentChatUser">
        <div style="display: flex; align-items: center; width: 100%;">
          <el-button
            type="text"
            style="margin-right: 10px; font-size: 20px; color: var(--icon-color);"
          >
            <el-icon><Mug /></el-icon> <!-- 表情图标 -->
          </el-button>
          <el-upload
            :show-file-list="false"
            :before-upload="handleFileUpload"
            :http-request="uploadFile"
          >
            <el-button type="text" style="margin-right: 10px; font-size: 20px; color: var(--icon-color);">
              <el-icon><Paperclip /></el-icon> <!-- 附件图标 -->
            </el-button>
          </el-upload>
          <el-input
            v-model="messageText"
            type="textarea"
            :rows="1"
            placeholder="输入消息..."
            @keyup.enter.ctrl="sendMessage"
            style="flex: 1; margin-right: 10px;"
          />
          <el-button
            type="primary"
            style="height: 40px; padding: 0 20px;"
            @click="sendMessage"
          >
            发送
          </el-button>
        </div>
      </div>

      <!-- 未选择用户时的提示 -->
      <div v-else style="flex: 1; display: flex; align-items: center; justify-content: center; color: #999;">
        请选择一个用户开始聊天
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Upload,
  Fold,
  Search, // 引入搜索图标
  Phone, // 引入电话图标
  VideoCamera, // 引入视频图标
  MoreFilled, // 引入更多图标
  Mug, // 引入表情图标
  Paperclip, // 引入附件图标
  UserFilled, // 引入人头图标
  Setting, // 引入设置图标
  SwitchButton // 引入退出图标
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useChatStore } from '@/stores/chat'
import { fileApi } from '@/api/file'
import dayjs from 'dayjs'
import { storeToRefs } from 'pinia'

const router = useRouter()
const authStore = useAuthStore()
const chatStore = useChatStore()

const messagesRef = ref()
const messageText = ref('')
const isSidebarOpen = ref(false)
const isMobile = ref(false)
const searchKeyword = ref('') // 新增搜索关键词

// 使用 storeToRefs 来正确地解构 Pinia store 中的反应性属性
const { currentUser, users, messages, currentChatUser } = storeToRefs(chatStore)

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

onMounted(async () => {
  await chatStore.loadUsers()
  console.log('Users loaded:', users.value)
  // 连接WebSocket
  chatStore.connectWebSocket()
  // 监听窗口大小变化
  window.addEventListener('resize', checkMobile);
  checkMobile(); // 初始化判断
})

onUnmounted(() => {
  // 断开WebSocket连接
  chatStore.disconnectWebSocket()
  // 移除窗口大小监听
  window.removeEventListener('resize', checkMobile);
})

const toggleSidebar = () => {
  isSidebarOpen.value = !isSidebarOpen.value;
};

const closeSidebarOnMobile = () => {
  if (isMobile.value && isSidebarOpen.value) {
    isSidebarOpen.value = false; // 在移动端点击主区域时关闭侧边栏
  }
};

const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768; // 根据屏幕宽度判断是否是移动端
  // PC端默认侧边栏开启，移动端默认侧边栏关闭
  isSidebarOpen.value = !isMobile.value;
};

const selectUser = async (user) => {
  console.log('Selecting user:', user)
  chatStore.setCurrentChatUser(user)
  chatStore.clearMessages()
  await chatStore.loadMessages(user.id)
  if (isMobile.value) {
    isSidebarOpen.value = false; // 移动端选择用户后关闭侧边栏
  }
}

const sendMessage = async () => {
  if (!messageText.value.trim() || !currentChatUser.value) return

  const result = await chatStore.sendMessage(messageText.value, currentChatUser.value.id)

  if (result.success) {
    messageText.value = ''
  } else {
    ElMessage.error(result.message)
  }
}

const recallMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm('确定要撤回这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await chatStore.recallMessage(messageId)

    if (result.success) {
      ElMessage.success('消息已撤回')
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    if (error !== 'cancel') { // 避免点击取消按钮时弹出错误
      ElMessage.error(error.message || '撤回失败')
    }
  }
}

const formatTime = (time) => {
  return dayjs(time).format('HH:mm')
}

const formatFileSize = (size) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  }
}

const downloadFile = (url, fileName) => {
  window.open(url, '_blank')
}

const handleFileUpload = (rawFile) => {
  // 可以在这里进行文件类型和大小的校验
  return true;
}

const uploadFile = async (options) => {
  try {
    const formData = new FormData();
    formData.append('file', options.file);
    const response = await fileApi.uploadFile(formData);

    if (response.data.code === 200) {
      const fileUrl = response.data.data.fileUrl;
      const fileName = options.file.name;
      const fileSize = options.file.size;
      await chatStore.sendMessage(fileUrl, currentChatUser.value.id, 'FILE', fileUrl, fileName, fileSize);
      ElMessage.success('文件发送成功');
    } else {
      ElMessage.error(response.data.message || '文件上传失败');
    }
  } catch (error) {
    console.error('文件上传失败:', error);
    ElMessage.error('文件上传失败');
  }
}

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    authStore.logout()
    router.push('/login')
    ElMessage.success('已退出登录')
  }).catch(() => {
    // 用户取消退出
  })
}

// 新增：导航到设置页面
const goToSettings = () => {
  router.push('/settings')
}

const scrollToBottom = () => {
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

const canRecall = (createdAt) => {
  const now = dayjs()
  const messageTime = dayjs(createdAt)
  return now.diff(messageTime, 'minute') < 1
}
</script>

<style scoped>
/* 这里可以放置组件特有的样式 */
.sidebar-header {
  padding: 15px 20px;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--sidebar-bg);
}

.current-user-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.current-user-info .user-avatar {
  width: 48px;
  height: 48px;
  margin-right: 12px;
  font-size: 16px;
  background-color: var(--primary-color);
  flex-shrink: 0;
}

.current-user-info .user-name {
  font-weight: 600;
  color: var(--text-color-dark);
  flex: 1;
  font-size: 16px;
}

.search-box .el-input {
  border-radius: var(--border-radius-small);
}

.search-box .el-input__wrapper {
  background-color: var(--input-bg);
  border-radius: var(--border-radius-small);
  padding: 5px 10px;
}

.search-box .el-input__inner {
  font-size: 14px;
}

.user-item-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-left: 10px;
}

.user-item-meta .message-time {
  font-size: 10px;
  color: var(--text-color-light);
  margin-bottom: 5px;
}

.last-message {
  font-size: 13px;
  color: var(--text-color-light);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px; /* 控制最后一条消息的宽度 */
}

.chat-header-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.chat-header-left .user-avatar {
  width: 40px; /* 聊天头部头像 */
  height: 40px;
  margin-right: 12px;
  font-size: 14px;
  background-color: #999; /* 默认头像颜色 */
}

.chat-header-name {
  font-weight: 600;
  font-size: 16px;
  color: var(--text-color-dark);
}

.chat-header-status {
  font-size: 11px;
  color: var(--text-color-light);
  display: flex;
  align-items: center;
}

.chat-header-right {
  display: flex;
  align-items: center;
  gap: 15px; /* 按钮间距 */
}

.chat-header-right .el-button {
  font-size: 20px;
  padding: 0;
  min-height: auto;
}

/* 覆盖 Element Plus textarea 的一些样式 */
.chat-input .el-textarea {
  border-radius: var(--border-radius-medium);
}

.chat-input .el-textarea__inner {
  resize: none; /* 禁止用户拖动改变大小 */
  padding: 10px 15px;
  min-height: 40px !important; /* 最小高度 */
  border-radius: var(--border-radius-medium);
  background-color: var(--input-bg);
  border: 1px solid var(--border-color);
  font-size: 15px;
}

.chat-input .el-textarea__inner:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 1px var(--primary-color);
}

.chat-input .el-button--primary {
  border-radius: var(--border-radius-medium);
  padding: 8px 20px;
  height: auto;
}

/* 消息气泡小箭头 */
.message-item .message-content::before {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border-style: solid;
  top: 10px; /* 调整箭头位置 */
}

.message-item:not(.own) .message-content::before {
  border-width: 0 8px 8px 0; /* 左侧箭头 */
  border-color: transparent var(--bubble-received) transparent transparent;
  left: -7px;
}

.message-item.own .message-content::before {
  border-width: 0 0 8px 8px; /* 右侧箭头 */
  border-color: transparent transparent transparent var(--bubble-sent-end);
  right: -7px;
}

/* 移动端特殊样式调整 */
@media (max-width: 768px) {
  .chat-sidebar {
    position: fixed; /* 使用 fixed 代替 absolute */
    height: 100vh; /* 移动端全高 */
    top: 0;
    left: 0;
    width: 75%; /* 移动端侧边栏宽度 */
    max-width: 300px; /* 最大宽度限制 */
    z-index: 1000; /* 确保在最顶层 */
    box-shadow: 2px 0 10px rgba(0, 0, 0, 0.2);
    border-radius: 0; /* 移动端移除圆角 */
  }

  .sidebar-header {
    padding: 10px 15px;
  }

  .current-user-info {
    margin-bottom: 10px;
  }

  .current-user-info .user-avatar {
    width: 40px;
    height: 40px;
    font-size: 14px;
  }

  .current-user-info .user-name {
    font-size: 14px;
  }

  .search-box {
    margin-top: 10px;
  }

  .user-list {
    padding: 10px 0;
  }

  .user-item {
    margin: 0 10px 5px 10px;
    padding: 8px 10px;
  }

  .user-item .user-avatar {
    width: 40px;
    height: 40px;
    font-size: 14px;
  }

  .user-name, .last-message {
    font-size: 13px;
  }

  .message-time, .user-status {
    font-size: 10px;
  }

  .chat-header {
    height: 60px;
    padding: 0 15px;
  }

  .chat-header-left .user-avatar {
    width: 36px;
    height: 36px;
    font-size: 12px;
    margin-right: 8px;
  }

  .chat-header-name {
    font-size: 14px;
  }

  .chat-header-right .el-button {
    font-size: 18px;
    gap: 10px;
  }

  .chat-messages {
    padding: 15px;
  }

  .chat-input {
    height: 80px;
    padding: 8px 15px;
  }

  .chat-input .el-textarea__inner {
    min-height: 36px !important;
  }
}
</style> 